﻿#include "game_logic.h"
#include "GameServer.h"
#include "ManagerHelper.h"
#include "../share/MessageDef.h"
#include "script_define.h"
#include "../share/GameHostManager.h"
#include "playerinfo_mgr.h"
#include "../share/proxyclient_service.h"
#include "scene_logic.h"
#include "sceneobj_manager.h"
#include "Fixed1024.h"
#include "MapSlot.h"
#include "scene_event.h"
#include "../share/time_module.h"
#include "../share/dirtyword.h"
#include "../share/tplmgr.h"

void CGameLogic::Initialize()
{
	registe_client_msg(common_wild_dig_operation_req, CGameLogic::SWildDigOperation);
	registe_client_msg(common_offer_reward_mission_new_list_req, CGameLogic::SUpdateOfferRewardMissionList);
	registe_client_msg(common_title_wear_or_takeoff_req, CGameLogic::STitleTakeOffOrWear);
	registe_client_msg(common_title_list_req, CGameLogic::STitleList);
	registe_client_msg(common_accept_mission_target_info_req, CGameLogic::STemp_AcceptMainTaskTargetInfo);
	registe_client_msg(s_set_player_hp, CGameLogic::SSetPlayerHp);
	registe_client_msg(guide_set_state_req, CGameLogic::SSetGuidState);
	registe_client_msg(player_relay_req, CGameLogic::SRelayMessage);
	//registe_client_msg(player_walk, CGameLogic::SPlayerWalkInfo); to map
	registe_client_msg(s_player_rocker_state, CGameLogic::SPlayerRockerState);
	
	//registe_client_msg(s_player_load_scene_finished, CGameLogic::SPlayerLoadSceneFinished);
	//registe_client_msg(s_player_change_scene, CGameLogic::SPlayerChangeScene); to map
	registe_client_msg(player_ping_req, CGameLogic::SPing);
	registe_client_msg(common_open_mission_dialog_req, CGameLogic::SOpenMissionDialog);
	registe_client_msg(common_offer_reward_mission_operation_req, CGameLogic::SOfferRewardMissionOperation);
	registe_client_msg(common_mission_move_complete_req, CGameLogic::SMissionMovePosition);
	registe_client_msg(common_mission_killmonster_complete_req, CGameLogic::SMissionKillMonster);
	registe_client_msg(common_mission_dungeon_complete_req, CGameLogic::SMissionDungeon);
	registe_client_msg(common_mission_collect_complete_req, CGameLogic::SMissionCollect);
	//registe_client_msg(s_lose_blood_req, CGameLogic::SLoseBlood); to map
	registe_client_msg(login_player_quit_game_notify, CGameLogic::SLoginPlayerQuitGameNotify);
	registe_client_msg(gate_close_client_fd_req, CGameLogic::SLoginPlayerQuitGameNotify);
	//registe_client_msg(player_heal_req, CGameLogic::SHeal);
	registe_client_msg(guide_ask_for_event_req, CGameLogic::SGuideAskEvent);
	registe_client_msg(gm_message_req, CGameLogic::SGmCommon);
	registe_client_msg(common_get_reward_props_req, CGameLogic::SGetRewardPropsCommon);
	registe_client_msg(lua_general_message_req, CGameLogic::SGeneralLuaMessage);
	registe_client_msg(c_player_Fixed_info_req, CGameLogic::SFixed1024InfoByErea);
	registe_client_msg(common_click_npc_req, CGameLogic::SClickNPC);
	registe_client_msg(common_ask_offer_reward_mission_req, CGameLogic::SAskMissionOfferList);
	registe_client_msg(common_mission_list_req, CGameLogic::SAskMissionList);
	registe_client_msg(common_ask_daily_mission_req, CGameLogic::SAskMissionDailyList);
	registe_client_msg(common_mission_complete_list_req, CGameLogic::SAskMissionComplete);
	registe_client_msg(common_mission_box_info_req, CGameLogic::SAskMissionBoxInfo);
	registe_client_msg(s_player_attack_req, CGameLogic::SPlayerAttack);
	registe_client_msg(s_player_guide_info_req, CGameLogic::SAskForGuideInfo);
	registe_client_msg(login_change_name_req, CGameLogic::PlayerChangeName);

	registe_server_msg(lua_general_message_req, CGameLogic::SGeneralLuaMessageServer);
	// registe_server_msg(db_player_rechanged_notify, CGameLogic::DGPlayerRechangedNotify);
	registe_server_msg(l2g_create_player_req, CGameLogic::L2GCreatePlayerRequest);
	registe_server_msg(d2g_create_player_ret, CGameLogic::D2GCreatePlayerResponse);
	registe_server_msg(l2g_player_login_req, CGameLogic::L2GPlayerLoginRequest);
	registe_server_msg(l2g_login_check_account_req, CGameLogic::L2GPlayerLoginCheckAccountRequest);
	registe_server_msg(d2g_load_player_ret, CGameLogic::D2GLoadPlayerResponse);
	registe_server_msg(map_player_login_again_notify, CGameLogic::MapPlayerLoginAgain);// 接收map过来的重新登录的消息
	registe_server_msg(plat_g_change_map_res, CGameLogic::G2GateChangeMapConnect);
	registe_server_msg(M2G_REVIVE_EVENT, CGameLogic::SPlayerRevive);
	registe_server_msg(M2G_SCENE_FOR_CLIENT, CGameLogic::SPlayerChangeScene);
	registe_server_msg(M2G_SYNC_HERO_REQUEST, CGameLogic::SyncHeroGame2Map);

}

void CGameLogic::SWildDigOperation(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;
	const Json::Value& m_jv = msg.GetJsonValue();

	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	uint32_t playerId = m_jv["playerId"].asUInt();
	uint32_t account = m_jv["account"].asUInt();

	player.OpenWildDig();

	_safe_guard_end;
}

void CGameLogic::SUpdateOfferRewardMissionList(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;
	const Json::Value& m_jv = msg.GetJsonValue();

	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	uint32_t playerId = m_jv["playerId"].asUInt();
	uint32_t account = m_jv["account"].asUInt();

	player.UpdateOfferRewardMissionNewList();

	_safe_guard_end;
}

void CGameLogic::STitleTakeOffOrWear(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;
	const Json::Value& m_jv = msg.GetJsonValue();

	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	uint32_t playerId = m_jv["playerId"].asUInt();
	uint32_t titleId = m_jv["titleId"].asUInt();
	uint32_t oprType = m_jv["oprType"].asUInt();//1穿2卸

	player.WearOrTakeOffTitle(titleId, oprType);

	_safe_guard_end;
}

void CGameLogic::STitleList(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;
	const Json::Value& m_jv = msg.GetJsonValue();

	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	uint32_t playerId = m_jv["playerId"].asUInt();

	player.GetTitleList();

	_safe_guard_end;
}

void CGameLogic::STemp_AcceptMainTaskTargetInfo(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;

	LOG_DEBUG("default","STemp_AcceptMainTaskTargetInfo::HandleMessage() -> enter ...");
	const Json::Value& m_jv = msg.GetJsonValue();
	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	uint32_t _missionId = m_jv["arg1"].asUInt();
	// int32_t _scriptId = (int32_t)m_jv["arg2"].asUInt();

	LOG_DEBUG("default","STemp_AcceptMainTaskTargetInfo::HandleMessage() -> _missionId:%d", _missionId);
	if (0 == _missionId)
	{
		return;
	}

	uint32_t _usrPosId = player.GetSn();
	uint32_t playerId = player.GetPlayerId();

	LOG_DEBUG("default","STemp_AcceptMainTaskTargetInfo::HandleMessage() -> _usrPosId:%d", playerId);
	if (MapSlot::GetInstance().GetLuaManagerPtr()->TryLock())
	{
		MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_MissionTrunkScript,
			LUA_AcceptMissionTargetInfo, playerId, _missionId);
	}
	else
	{
		MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_MissionTrunkScript,
			LUA_AcceptMissionTargetInfo, playerId, _missionId);
		LOG_ERROR("default","MapSlot::GetInstance().GetLuaManagerPtr()->TryLock()");
	}
	LOG_DEBUG("default","STemp_AcceptMainTaskTargetInfo::HandleMessage() -> out ...");
	_safe_guard_end;
}

void CGameLogic::SSetPlayerHp(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;
	const Json::Value& m_jv = msg.GetJsonValue();
	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	int32_t	_hp = m_jv["hp"].asUInt();

	if (_hp <= 0)
	{
		_hp = 0;
	}

	//pplayer->SetHp(_hp);
	//pplayer->SetMaxHp(_hp);

	_safe_guard_end;
}

void CGameLogic::SSetGuidState(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;
	const Json::Value& m_jv = msg.GetJsonValue();

	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	uint32_t playerId = m_jv["playerId"].asUInt();
	uint32_t accountId = m_jv["account"].asUInt();
	uint32_t _idx = m_jv["arg1"].asUInt();
	uint32_t _iidx = m_jv["arg2"].asUInt();
	uint32_t _val = m_jv["arg3"].asUInt();

	//[废]pplayer->SetGuideState(_idx, _iidx, 1, _val);


	_safe_guard_end;
}

void CGameLogic::SRelayMessage(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;
	const Json::Value& m_jv = msg.GetJsonValue();

	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	if (!m_jv.isMember("msg"))
	{
		return;
	}

	_safe_guard_end;
}


void CGameLogic::SPlayerRockerState(Player& player, const CJsonMessageBase& msg)
{
	return;
}

void CGameLogic::SPlayerRevive(const ::common::CProxyHead& head, const CJsonMessageBase& msg)
{
	_safe_guard_begin;
	const Json::Value& m_jv = msg.GetJsonValue();
	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	uint32_t _sor_key = m_jv["sk"].asUInt();
	uint32_t _tar_key = m_jv["tk"].asUInt();
	int32_t _revive_type = m_jv["rt"].asInt();
	uint32_t playerId = m_jv["playerId"].asUInt();

	Player* player = CSceneLogic::GetInstance().GetPlayerByPlayerID(playerId);

	if (player == nullptr) {
		return;
	}

	if (0 == _tar_key)
	{
		//	_tar_key为0，则指用户自己

		MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_PlayerManagerScript,
			LUA_PlayerRevive, player->GetPlayerId());
	}
	else
	{

	}

	_safe_guard_end;
}


void CGameLogic::SPlayerChangeScene(const ::common::CProxyHead& head, const CJsonMessageBase& msg)
{
	_safe_guard_begin;

	LOG_DEBUG("default","Game Server: SPlayerChangeScene start.");
	const Json::Value& m_jv = msg.GetJsonValue();
	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	uint32_t _from = m_jv["fr"].asUInt();
	uint32_t _to = m_jv["to"].asUInt();
	int32_t _flag = m_jv["fl"].asInt();
	uint32_t playerId = m_jv["playerId"].asUInt();

	//	1：区域内检查的自动跳转
	//	2：指定跳转
	if (1 != _flag && 2 != _flag)
	{
		return;
	}

	Player* player = CSceneLogic::GetInstance().GetPlayerByPlayerID(playerId);
	if (player == NULL) {
		LOG_ERROR("default", "player change client scene error player is null");
		return;
	}

	// 强制flag是1 跳转到客户端副本场景
	_flag = 1;
	player->ChangeScene(_flag, _to, _from);

	LOG_DEBUG("default","Game Server: SPlayerChangeScene over.");

	_safe_guard_end;
}

void CGameLogic::SPing(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;

	const Json::Value& m_jv = msg.GetJsonValue();
	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	uint32_t _key = m_jv["key"].asUInt();
	uint32_t _ch = m_jv["ch"].asUInt();
	uint32_t _cl = m_jv["cl"].asUInt();

	player.UpdatePlayerInfoPing();

	player.SetPingTime(_ch, _cl);

	// 发送给map的ping消息
	Json::Value ping_json = m_jv;
	ping_json["playerId"] = player.GetPlayerId();
	ping_json["msgid"] = player_map_ping_req;
	std::string str = JsonWriter(ping_json);
	send_2_map(player_map_ping_req, str);

	_safe_guard_end;
}

void CGameLogic::SOpenMissionDialog(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;


	/*临时：屏蔽任务接取*/
	//pplayer->SendErrMessage();
	//return;
	const Json::Value& m_jv = msg.GetJsonValue();
	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	int32_t missionId = (int32_t)m_jv["taskId"].asUInt();
	int32_t PlayerSelect = (int32_t)m_jv["PlayerSelect"].asUInt();

	int32_t paramFirst = (int32_t)m_jv["paramFirst"].asUInt();
	int32_t paramSecond = (int32_t)m_jv["paramSecond"].asUInt();
	int32_t thrdPram = (int32_t)m_jv["thrdPram"].asUInt();
	int32_t fourPram = (int32_t)m_jv["fourPram"].asUInt();

	int32_t playerId = player.GetPlayerId();

	if (MapSlot::GetInstance().GetLuaManagerPtr()->TryLock())
	{
		MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction((int32_t)LUA_MissionTrunkScript, LUA_MissionDialogue
			, (int32_t)playerId, (int32_t)missionId,(int32_t)PlayerSelect, (int32_t)paramFirst,
			(int32_t)paramSecond, (int32_t)thrdPram,(int32_t)fourPram);
	}
	else
	{
		MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction((int32_t)LUA_MissionTrunkScript, LUA_MissionDialogue
			, (int32_t)playerId, (int32_t)missionId, (int32_t)PlayerSelect, (int32_t)paramFirst,
			(int32_t)paramSecond, (int32_t)thrdPram, (int32_t)fourPram);
	}

	_safe_guard_end;
}

void CGameLogic::SOfferRewardMissionOperation(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;


	LOG_DEBUG("default","S OFFER REWARD MISSION OPERATION : HANDLE MESSAGE ! \n\n\n");

	const Json::Value& m_jv = msg.GetJsonValue();
	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	uint32_t playerId = m_jv["playerId"].asUInt();
	uint32_t account = m_jv["account"].asUInt();
	uint32_t missionClientPos = m_jv["arg1"].asUInt();
	uint32_t operationType = m_jv["arg2"].asUInt();

	player.OperationOfferRewardMission(missionClientPos, operationType);

	_safe_guard_end;
}

void CGameLogic::SMissionMovePosition(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;

	const Json::Value& m_jv = msg.GetJsonValue();
	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	uint32_t missionId = m_jv["missionId"].asUInt();
	uint32_t posX = (uint32_t)(m_jv["posX"].asDouble() * 1000000);
	uint32_t posZ = (uint32_t)(m_jv["posZ"].asDouble() * 1000000);

	uint32_t missionType = m_jv["arg1"].asUInt();

	if (e_mission_type_main == missionType)
	{
		player.MoveToPositionMisson(missionId, posX, posZ);
	}
	else if (e_mission_type_reward == missionType)
	{
		uint32_t _npcId = missionId;
		player.WildDeliveryMoveToNpc(_npcId, posX, posZ);
	}


	_safe_guard_end;
}

void CGameLogic::SMissionKillMonster(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;

	const Json::Value& m_jv = msg.GetJsonValue();
	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	uint32_t monsterId = m_jv["monsterId"].asUInt();

	//主线杀怪
	player.KillMonsterMainMission(monsterId);

	//野外杀怪
	player.KillMonsterWildMission(monsterId);

	_safe_guard_end;
}

void CGameLogic::SMissionDungeon(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;

	const Json::Value& m_jv = msg.GetJsonValue();
	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	uint32_t dungeonId = m_jv["dungeonId"].asUInt();

	player.DungeonMission(dungeonId);

	_safe_guard_end;
}

void CGameLogic::SMissionCollect(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;

	const Json::Value& m_jv = msg.GetJsonValue();
	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	uint32_t itemId = m_jv["itemId"].asUInt();
	uint32_t allCount = m_jv["allCount"].asUInt();

	//uint32_t scenceType = m_jv["arg1"].asUInt();;//0:主线 1:悬赏

	//if (e_mission_type_main == scenceType)
	//{
	player.CollectMission(itemId, allCount);
	//}
	//else if (e_mission_type_reward == scenceType)
	//{
	player.WildCollet(itemId);
	//}

	_safe_guard_end;
}


void CGameLogic::SLoginPlayerQuitGameNotify(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;

	const Json::Value& m_jv = msg.GetJsonValue();
	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	CSceneLogic::GetInstance().PlayerLeaveGame(player);
	/*
	Json::Value jmsg;
	uint32_t account = m_jv["account"].asUInt();
	jmsg["areaId"] = GameHostManager::GetInstance().GetServerAreaId();
	jmsg["account"] = account;
	jmsg["playerId"] = m_jv["playerId"].asInt();

	std::string send_str = JsonWriter(jmsg);
	send_2_db(game_2_db_login_out, send_str, account);
	*/
	_safe_guard_end;
}

void CGameLogic::SHeal(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;

	const Json::Value& m_jv = msg.GetJsonValue();
	_safe_guard_end;
}

void CGameLogic::SGuideAskEvent(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;

	const Json::Value& m_jv = msg.GetJsonValue();
	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	uint32_t playerId = m_jv["playerId"].asUInt();
	uint32_t accountId = m_jv["account"].asUInt();
	uint32_t _uiId = m_jv["arg1"].asUInt();

	//[废]pplayer->AskGuideEvent(_uiId);


	_safe_guard_end;
}

void CGameLogic::SGmCommon(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;
	const Json::Value& m_jv = msg.GetJsonValue();
	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	uint32_t playerId = m_jv["playerId"].asUInt();
	uint32_t accountId = m_jv["account"].asUInt();
	uint32_t gmType = m_jv["arg1"].asUInt();
	uint32_t gmValue = m_jv["arg2"].asUInt();

	switch (gmType)
	{
	case 1://当前主线任务
	{
		player.GmCurrentMainMission(gmValue);
		break;
	}

	default:
		return;
	}

	_safe_guard_end;
}

void CGameLogic::SGetRewardPropsCommon(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;

	const Json::Value& m_jv = msg.GetJsonValue();
	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	uint32_t playerId = m_jv["playerId"].asUInt();
	uint32_t accountId = m_jv["account"].asUInt();
	uint32_t thisId = m_jv["arg1"].asUInt();
	uint32_t thisType = m_jv["arg2"].asUInt();
	uint32_t paramFirst = m_jv["arg3"].asUInt();
	uint32_t paramSecond = m_jv["arg4"].asUInt();

	switch (thisType)
	{
	case 1://日常任务奖励
	{
		player.GetDailyMissionRewardProps(thisId, paramFirst, paramSecond);
		break;
	}
	case 2://活跃奖励
	{
		player.GetActiveRewardBox(thisId, paramFirst, paramSecond);
		break;
	}
	case 3://野外挖宝奖励
	{
		player.GetWildDiaReward();
		break;
	}
	//...
	default:
		return;
	}


	_safe_guard_end;
}

void CGameLogic::SGeneralLuaMessage(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;
	const Json::Value& m_jv = msg.GetJsonValue();
	if (!m_jv.isMember("msgid"))
	{
		LOG_ERROR("default", "SGeneralLuaMessage have not msgid!");
		return;
	}

	//uint32_t sn = player.GetSn();
	uint32_t sn = player.GetPlayerId();
// 	if (m_jv["msgid"].asUInt() < 0x3000)
// 	{
// 		sn = player.GetSn();
// 	}
// 	else
// 	{
// 		sn = msg.GetFromSocketId();
// 	}

	std::string _val = JsonWriter(m_jv);

	///结算、扫荡
	if (MapSlot::GetInstance().GetLuaManagerPtr()->TryLock())
	{
		MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_MsgManagerScript,
			LUA_PaserMessage, sn, _val.c_str());
	}
	else
	{
		// MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_MsgManagerScript,
		//	LUA_PaserMessage, sn, _val.c_str());
		LOG_INFO("default","MapSlot::GetInstance().GetLuaManagerPtr() : TraLock() false.!");
	}

	///任务相关部分(解：RunScriptFunction调用)
	uint32_t _msgId = m_jv["msgid"].asUInt();
	switch (_msgId)
	{
	case pve_dungeon_settlement_req:
	{
		uint32_t _dungeonId = m_jv["arg2"].asUInt();
		uint32_t _result = m_jv["arg3"].asUInt();//2成功
		uint32_t _types = m_jv["arg5"].asUInt();//1普通副本

		if (1 == _types && 2 == _result)
		{
			//主线任务：通关某一个指定id副本条件
			player.DungeonMission(_dungeonId);
		}
		else if (2 == _types)
		{
			//日常任务(7)：通关精英副本1次 --lua中指定脚本处理
		}

		break;
	}
	case pve_flash_dungeon_req:
	{
		//存在扫荡完成任务的情况
		uint32_t _dungeonId = m_jv["arg2"].asUInt();
		player.DungeonMission(_dungeonId);

		break;
	}

	default:
		break;
	}

	_safe_guard_end;
}

void CGameLogic::SFixed1024InfoByErea(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;

	const Json::Value& m_jv = msg.GetJsonValue();
	if (!m_jv.isMember("msgid"))
		return;

	uint32_t _playerId = m_jv["playerId"].asUInt();

	uint32_t _minVal = m_jv["arg1"].asUInt();
	uint32_t _maxVal = m_jv["arg2"].asUInt();

	player.GetFixed1024InfoByErea(_minVal, _maxVal);


	_safe_guard_end;
}

void CGameLogic::SClickNPC(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;
	const Json::Value& m_jv = msg.GetJsonValue();
	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	uint32_t npcId = m_jv["npcId"].asUInt();
	uint32_t paramFirst = m_jv["paramFirst"].asUInt();
	uint32_t paramSecond = m_jv["paramSecond"].asUInt();

	uint32_t scenceType = m_jv["arg1"].asUInt();//0:主线 1:支线2:悬赏

												//test
												//npcId = 4294700000;
												//!test

	LOG_DEBUG("default", "CGameLogic::SClickNPC playerId = %d scenceType = %d", player.GetPlayerId(), scenceType);

	if (e_mission_type_main == scenceType)
	{
		player.ClickNpc(npcId, paramFirst, paramSecond);
	}
	else if (e_mission_type_reward == scenceType)
	{
		player.WildDeliveryDone();
	}

	_safe_guard_end;
}

void CGameLogic::SAskMissionOfferList(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;



	//std::cout << "== == == == == ==" << std::endl;
	//std::cout << "ACCEPT OFFER REWARD ASK MSG!!" << std::endl;
	//std::cout << "== == ==" << std::endl;
	const Json::Value& m_jv = msg.GetJsonValue();
	LOG_DEBUG("default","== == == == == ==\n");
	LOG_DEBUG("default","ACCEPT OFFER REWARD ASK MSG!!\n");
	LOG_DEBUG("default","== == ==\n");

	
	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	uint32_t playerId = m_jv["playerId"].asUInt();
	uint32_t account = m_jv["account"].asUInt();

	//获取悬赏任务列表
	player.AskOfferRewardMissionList();

	_safe_guard_end;
}

void CGameLogic::SAskMissionList(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;

	const Json::Value& m_jv = msg.GetJsonValue();
	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	player.GetMissionList();

	_safe_guard_end;
}

void CGameLogic::SAskMissionDailyList(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;

	const Json::Value& m_jv = msg.GetJsonValue();
	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	uint32_t playerId = m_jv["playerId"].asUInt();
	uint32_t account = m_jv["account"].asUInt();

	//获取日常任务列表 有则读取  无则存入
	player.AskDailyMissionList();

	_safe_guard_end;
}

void CGameLogic::SAskMissionComplete(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;

	const Json::Value& m_jv = msg.GetJsonValue();
	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	player.GetMissionCompleteState();

	_safe_guard_end;
}

void CGameLogic::SAskMissionBoxInfo(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;
	const Json::Value& m_jv = msg.GetJsonValue();
	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	uint32_t playerId = m_jv["playerId"].asUInt();

	player.GetMissionBoxInfoToClient();

	_safe_guard_end;
}

void CGameLogic::SPlayerAttack(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;
	const Json::Value& m_jv = msg.GetJsonValue();
	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	//uint32_t _tar_key = m_jv["tk"].asUInt();	//	目标id
	//int32_t _skill_id = m_jv["sd"].asInt();		//	技能id
	//double _pos_x = m_jv["sx"].asDouble();		//	源x位置
	//double _pos_y = m_jv["sy"].asDouble();		//	源y位置
	//double _pos_z = m_jv["sz"].asDouble();		//	源z位置
	//double _orientation_x = m_jv["dx"].asDouble();		//	源x朝向
	//double _orientation_y = m_jv["dy"].asDouble();		//	源y朝向
	//double _orientation_z = m_jv["dz"].asDouble();		//	源z朝向
	//double _target_x = m_jv["tx"].asDouble();		//	目标x位置
	//double _target_y = m_jv["ty"].asDouble();		//	目标x位置
	//double _target_z = m_jv["tz"].asDouble();		//	目标x位置

	//player.PlayerAttack(_tar_key, _skill_id,
	//	_pos_x, _pos_y, _pos_z,
	//	_orientation_x, _orientation_y, _orientation_z,
	//	_target_x, _target_y, _target_z
	//);

	_safe_guard_end;
}

void CGameLogic::SGeneralLuaMessageServer(const common::CProxyHead& head, const CJsonMessageBase& msg)
{
	_safe_guard_begin;

	const Json::Value& m_jv = msg.GetJsonValue();

	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	uint32_t socketId = msg.GetFromSocketId();

	std::string _val = JsonWriter(m_jv);

	if (MapSlot::GetInstance().GetLuaManagerPtr()->TryLock())
	{
		MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_MsgManagerScript,
			LUA_PaserMessage, socketId, _val.c_str());
	}
	else
	{
		MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_MsgManagerScript,
			LUA_PaserMessage, socketId, _val.c_str());
		LOG_INFO("default","MapSlot::GetInstance().GetLuaManagerPtr() : TraLock() false.!");
	}

	_safe_guard_end;
}

void CGameLogic::SAskForGuideInfo(Player& player, const CJsonMessageBase& msg)
{
	_safe_guard_begin;

// 	if (!pplayer)
// 	{
// 		return;
// 	}
// 	_safe_check(pplayer);
// 
// 	if (!m_jv.isMember("msgid"))
// 	{
// 		return;
// 	}
// 
// 	uint32_t _sn = m_jv["sp"].asUInt();
// 
// 	//[废]pplayer->AskForGuideInfo(_sn);

	_safe_guard_end;
}

void CGameLogic::L2GCreatePlayerRequest(const common::CProxyHead& head, const CJsonMessageBase& msg)
{
	_safe_guard_begin;
	const Json::Value& m_jv = msg.GetJsonValue();
	std::string name = m_jv["name"].asString();
	uint32_t account = m_jv["account"].asUInt();
	uint32_t heroId = m_jv["heroId"].asUInt();

	// 查询在该服上有没有角色存在
	int32_t player_id = CPlayerInfoMgr::GetInstance().GetPlayerIDbyAccountID(account);
	if ( player_id > 0 )
	{
		Json::Value jmsg;
		jmsg["ret"] = ::common::ERR_LOGIN_CREATE_HAS_PLAYER;
		jmsg["account"] = account;
		std::string send_str = JsonWriter(jmsg);
		send_2_login(g2l_create_player_ret, send_str);
		LOG_ERROR("default","Create Role Faild, player is exist![%d:%d]", account, player_id);
		return;
	}

	// 已经有对应的角色名存在了
	CPlayerInfo* playerinfo = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerName(name);
	if ( playerinfo != NULL )
	{
		Json::Value jmsg;
		jmsg["ret"] = ::common::ERR_LOGIN_CREATE_HAS_NAME;
		jmsg["account"] = account;
		std::string send_str = JsonWriter(jmsg);
		send_2_login(g2l_create_player_ret, send_str);
		LOG_ERROR("default","Create Role Faild, role_name is exists, account_id %d role_id %d", account, player_id);
		return;
	}

	player_id = CPlayerInfoMgr::GetInstance().GetAccoutRoleIDMax() + 1;
	if ( player_id > 1048575)
	{
		LOG_ERROR("default","player_id is too big! %d", player_id);
		Json::Value jmsg;
		jmsg["ret"] = ::common::ERR_SERVERCFG_ERR;
		jmsg["account"] = account;
		std::string send_str = JsonWriter(jmsg);
		send_2_login(g2l_create_player_ret, send_str);
		return;
	}
	// 服务器只能支持2047个区服ID，在一个大区，用一个worldProxy管理，支持合服
	int32_t areaid = GameHostManager::GetInstance().GetServerAreaId();
	if ( areaid > 2047 )
	{
		LOG_ERROR("default","areaid is too big! %d", areaid);
		Json::Value jmsg;
		jmsg["ret"] = ::common::ERR_SERVERCFG_ERR;
		jmsg["account"] = account;
		std::string send_str = JsonWriter(jmsg);
		send_2_login(g2l_create_player_ret, send_str);
		return;
	}
	player_id = (areaid << 20) | player_id;

	if (account == 0 || heroId == 0 || name.empty() || player_id == 0)
	{
		LOG_ERROR("default","Create Role Faild , account_id %d role_id %d session %d", account, player_id);
		Json::Value jmsg;
		jmsg["ret"] = ::common::ERR_UNKNOWN;
		jmsg["account"] = account;
		std::string send_str = JsonWriter(jmsg);
		send_2_login(g2l_create_player_ret, send_str);
		return;
	}

	// 判断英雄选择是否正确
	// TODO


	// 发送到DB去创建角色
	Json::Value jmsg;
	jmsg["account"] = account;
	jmsg["playerId"] = player_id;
	jmsg["heroId"] = heroId;
	jmsg["name"] = name;
	jmsg["areaId"] = GameHostManager::GetInstance().GetServerAreaId();
	jmsg["createtime"] = (int32_t)CUR_SEC;
	jmsg["udid"] = m_jv["udid"].asString();
	jmsg["appKey"] = m_jv["appKey"].asString();
	jmsg["appSecret"] = m_jv["appSecret"].asString();
	jmsg["pubKey"] = m_jv["pubKey"].asString();

	std::string send_str = JsonWriter(jmsg);
	send_2_db(g2d_create_player_req, send_str, account);
	return;

	_safe_guard_end;
}

void CGameLogic::D2GCreatePlayerResponse(const common::CProxyHead& head, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	
	int32_t ret = m_jv["ret"].asInt();
	int32_t playerId = m_jv["playerId"].asInt();
	int32_t account = m_jv["account"].asInt();
	if (ret == ::common::SUCCEED)
	{
		do 
		{
			CPlayerInfo* player_info = new CPlayerInfo();
			if (player_info == NULL)
			{
				LOG_ERROR("default","new CPlayerInfo err!");
				ret = ::common::ERR_LOGIN_CREATE_PLAYER_INFO_ERR;
				break;
			}
			std::string name = m_jv["name"].asString();
			int32_t heroId = m_jv["heroId"].asInt();
			int32_t heroSkinId = m_jv["heroSkinId"].asInt();
			int32_t photoframe = m_jv["photoFrame"].asInt();
			int32_t photo = m_jv["photo"].asInt();

			player_info->set_accountId(account);
			player_info->set_playerId(playerId);
			player_info->set_name(name);
			player_info->set_level(1);
			player_info->set_heroid(heroId);
			player_info->set_heroSkinId(heroSkinId);
			player_info->set_vip(0);
			player_info->set_photoframe(photoframe);
			player_info->set_afc(0);
			player_info->set_union_id(0);
			player_info->set_union_name("");
			player_info->set_title(0);

			CPlayerInfoMgr::GetInstance().AddRole(player_info);

			Player* player = CSceneLogic::GetInstance().GetPlayerByPlayerID(playerId);
			if (player != NULL)
			{
				LOG_ERROR("default","[login] player is exits[%d][%d]", account, playerId);
				ret = ::common::ERR_LOGIN_CREATE_PLAYER_ERR;
				break;
			}

			player = CGameObjManager::GetInstance().CreateObject< Player >(OBJTYPE_PLAYER);
			if (player == NULL)
			{
				LOG_ERROR("default","[login] create player err[%d][%d]", account, playerId);
				ret = ::common::ERR_LOGIN_CREATE_PLAYER_ERR;
				break;
			}
			player->SetGameObject(GOT_PLAYER, playerId);
			player->SetKey(player_key_start + playerId);
			player->SetPlayerLuaState(MapSlot::GetInstance().GetLuaManagerPtr());
			player->SetPlayerId(playerId);
			player->SetAccount(account);
			player->SetName(name.c_str());
			player->SetHeroId(heroId);
			player->SetHeroSkinId(heroSkinId);
			player->SetLevel(1);
			player->SetPhoto(photo);
			player->SetPhotoFrame(photoframe);
			player->set_login_key(RAND(INT_MAX));
			player->set_player_state(Player::STATE_GAME);
			player->set_update_time(CUR_SEC);
			CSceneLogic::GetInstance().PlayerEnterGame(*player);

			// 在这执行玩家首次登陆吧
			std::string str = JsonWriter(m_jv);
			int32_t ret_code = MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_PlayerManagerScript,
				LUA_FirstLogin, playerId, str.c_str());
			if (ret_code != ::common::SUCCEED )
			{
				LOG_ERROR("default", " first login lua func err!playerid[%d]", playerId);
				ret = ::common::ERR_LOGIN_FIRST_LOGIN_LUA_ERR;
			}
		} while (0);
	}
	if ( ret != ::common::SUCCEED )
	{
		Json::Value response;
		response["ret"] = ret;
		response["playerId"] = playerId;
		response["account"] = account;
		std::string res = JsonWriter(response);
		send_2_login(g2l_create_player_ret, res);
		return;
	}
	
	CGameLogic::GetInstance().SendPlayerLoginResponse(playerId, g2l_create_player_ret);
}

void CGameLogic::L2GPlayerLoginRequest(const common::CProxyHead& head, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t account_id = m_jv["account"].asInt();
	int32_t playerId = m_jv["playerId"].asInt();
	
	CPlayerInfo* playerinfo = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(playerId);
	if (playerinfo == NULL )
	{
		LOG_ERROR("default","LoginErr playerinfo is null![%d][%d]", account_id, playerId);
		return;
	}
	if (playerinfo->get_accountId() != account_id )
	{
		LOG_ERROR("default","LoginErr player[%d][%d] mismatch account[%d]", account_id, playerId, playerinfo->get_accountId());
		return;
	}
	
	// 查看当前在线情况
	Player* player = CSceneLogic::GetInstance().GetPlayerByPlayerID(playerId);
	if (player != NULL )
	{
		LOG_ERROR("default","<LOGIN> player[%d][%d] is online!", account_id, playerId);
		// 将玩家踢下线,顶替掉
		player->KickPlayerNotify(1);
		CSceneLogic::GetInstance().PlayerLeaveGame(*player);
	}
	player = CGameObjManager::GetInstance().CreateObject< Player >(OBJTYPE_PLAYER);
	if (NULL == player)
	{
		LOG_ERROR("default","<LOGIN> create player failed %d", playerId);
		return;
	}
	player->SetGameObject(GOT_PLAYER, playerId);
	player->SetKey(player_key_start + playerId);
	player->SetPlayerLuaState(MapSlot::GetInstance().GetLuaManagerPtr());
	player->SetPlayerId(playerId);
	player->SetAccount(account_id);
	player->SetHeroId(playerinfo->get_heroid());
	player->SetHeroSkinId(playerinfo->get_heroSkinId());
	player->SetName(playerinfo->get_name().c_str());
	player->SetLevel(1);
	

	CSceneLogic::GetInstance().PlayerEnterGame(*player);

	Json::Value load_request;
	load_request["playerId"] = playerId;
	load_request["account"] = account_id;
	std::string req = JsonWriter(load_request);
	send_2_db(g2d_load_player_req, req, account_id);
	player->set_player_state(Player::STATE_LOADING);
}

void CGameLogic::L2GPlayerLoginCheckAccountRequest(const common::CProxyHead& head, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t account_id = m_jv["account"].asInt();

	int32_t playerId = CPlayerInfoMgr::GetInstance().GetPlayerIDbyAccountID(account_id);
	if (playerId <= 0)
	{
		Json::Value response;
		response["ret"] = ::common::SUCCEED;
		response["account"] = account_id;
		response["playerId"] = 0;
		response["name"] = "";
		response["heroId"] = 0;
		response["areaId"] = GameHostManager::GetInstance().GetServerAreaId();
		std::string res = JsonWriter(response);
		send_2_login(g2l_login_check_account_ret, res);
		return;
	}

	CPlayerInfo* player = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(playerId);
	if ( player == NULL )
	{
		Json::Value response;
		response["ret"] = ::common::ERR_CHECK_ACCOUNT_PLAYERINFO_ERR;
		response["account"] = account_id;
		std::string res = JsonWriter(response);
		send_2_login(g2l_login_check_account_ret, res);
		LOG_ERROR("default","CheckAccount player[%d][%d] is null", account_id, playerId);
		return;
	}

	Json::Value response;
	response["ret"] = ::common::SUCCEED;
	response["account"] = account_id;
	response["playerId"] = playerId;
	response["name"] = player->get_name();
	response["heroId"] = player->get_heroid();
	response["areaId"] = GameHostManager::GetInstance().GetServerAreaId();
	std::string res = JsonWriter(response);
	send_2_login(g2l_login_check_account_ret, res);
}

void CGameLogic::D2GLoadPlayerResponse(const common::CProxyHead& head, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t playerId = m_jv["playerId"].asInt();
	int32_t accountid = m_jv["account"].asInt();

	Player* player = CSceneLogic::GetInstance().GetPlayerByPlayerID(playerId);
	if (player == NULL)
	{
		LOG_ERROR("default","[load] player is null [%d]",playerId);
		return;
	}
	
	std::string player_info = m_jv["info"].asString();
	std::string player_detail = m_jv["detail"].asString();
	
	int32_t logintime = m_jv["loginTime"].asInt();
	LOG_INFO("default","load player[%d][%d] detail data %s", accountid, playerId, player_detail.c_str());
	// 目前只加载了detail数据
	int32_t ret_code = MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_PlayerManagerScript,
		LUA_DetailLoadFromDB, playerId, player_detail.c_str(), player_info.c_str());
	if ( ret_code != ::common::SUCCEED )
	{
		LOG_ERROR("default", "detail load from db err player[%d]", playerId);
		return;
	}

	player->set_login_key(RAND(INT_MAX));
	player->set_player_state(Player::STATE_GAME);
	Json::Value detail_json;
	JsonReader(player_detail, detail_json);
	player->LoadFromJson(detail_json);

	//MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_PlayerCommonScript,LUA_SaveSinglePlayerNewDailyTask, playerId);
	CGameLogic::GetInstance().SendPlayerLoginResponse(playerId, g2l_player_login_ret);
}

void CGameLogic::SendPlayerLoginResponse(int32_t playerId, int32_t msgid)
{
	Player* player = CSceneLogic::GetInstance().GetPlayerByPlayerID(playerId);
	if ( player == NULL )
	{
		LOG_ERROR("default","player is null");
		return;
	}
	Json::Value response;
	response["msgid"] = msgid;
	response["ret"] = ::common::SUCCEED;
	response["login_key"] = player->login_key();
	player->WriteDataToJson(response);
	std::string res = JsonWriter(response);
	send_2_login(msgid, res);
	//GameServer::GetInstance().client_msg_dispatch(res, player->GetSocketId(), msgid);
}

void CGameLogic::DGPlayerRechangedNotify(const common::CProxyHead& head, const CJsonMessageBase& msg)
{
	_safe_guard_begin;
	const Json::Value& m_jv = msg.GetJsonValue();
	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	uint32_t _accountId = m_jv["account"].asUInt();
	uint32_t _playerId = m_jv["playerId"].asUInt();
	uint32_t _diamond = m_jv["diamond"].asUInt();
	uint32_t _rmb = m_jv["rmb"].asUInt();

	Player* pp = CSceneLogic::GetInstance().GetPlayerByPlayerID(_playerId);
	if (nullptr != pp)
	{
		uint32_t diamond = pp->GetCurrency(Fixed1024::CURRENCY_DIAMOND) + _diamond;
		pp->SetCurrency(Fixed1024::CURRENCY_DIAMOND, diamond);
		pp->SetPlayerSomeInfoToRedisDB("diamond", diamond);
	}
	else
	{
		LOG_ERROR("default","RechangedNotify player[%d][%d] is not online! %d:%d", _accountId, _playerId, _diamond, _rmb);
	}

	_safe_guard_end;
}

int32_t CGameLogic::OnMsgC2GEnterGameRequest(int32_t fd, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int playerId = m_jv["playerId"].asInt();
	int32_t login_key = m_jv["login_key"].asInt();
	uint32_t _mapId = GameHostManager::GetInstance().GetMapId();

	if (m_jv.isMember("mapId"))
	{
		uint32_t tmpId = m_jv["mapId"].asUInt();
		if (tmpId > 0)
		{
			_mapId = m_jv["mapId"].asUInt();
		}
	}

	Player* player = CSceneLogic::GetInstance().GetPlayerByPlayerID(playerId);
	if (player == NULL)
	{
		Json::Value response;
		response["msgid"] = g2c_player_enter_game_ret;
		response["ret"] = ::common::ERECONNECT_PLAYER_NULL;
		response["playerId"] = playerId;
		std::string res = JsonWriter(response);
		GameServer::GetInstance().client_msg_dispatch(res, fd, g2c_player_enter_game_ret);
		LOG_ERROR("default","[login] player is null[%d]", playerId);
		return ::common::SUCCEED;
	}
	if (player->login_key() != login_key)
	{
		LOG_INFO("default","socket %d login request, playerid %d is online, login key %d %d ", fd, playerId,
			player->login_key(), login_key);
		Json::Value response;
		response["msgid"] = g2c_player_enter_game_ret;
		response["ret"] = ::common::ERECONNECT_SESSION_FAIL;
		response["playerId"] = playerId;
		std::string res = JsonWriter(response);
		GameServer::GetInstance().client_msg_dispatch(res, fd, g2c_player_enter_game_ret);
		CSceneLogic::GetInstance().CloseTcpConnect(fd);
		return common::SUCCEED;
	}

	if ( player->player_state() != Player::STATE_GAME)
	{
		LOG_INFO("default","socket %d login request, playerid %d is online, login key %d %d ", fd, playerId,
			player->login_key(), login_key);
		Json::Value response;
		response["msgid"] = g2c_player_enter_game_ret;
		response["ret"] = ::common::ERECONNECT_PLAYERSTATE_ERR;
		response["playerId"] = playerId;
		std::string res = JsonWriter(response);
		GameServer::GetInstance().client_msg_dispatch(res, fd, g2c_player_enter_game_ret);
		CSceneLogic::GetInstance().CloseTcpConnect(fd);
		return common::SUCCEED;
	}

	player->SetSocketId(fd);

	player->set_connected(true);
	player->SetNotEmpty();
	
	CSceneLogic::GetInstance().RegistePlayerSocket(fd, player->get_id());
	CSceneLogic::GetInstance().SetPlayerId2MidMap(playerId, _mapId);

	LOG_INFO("default","player[%d][%d] enter game succeed!", playerId, fd);

	// 这里要先 给map 然后在返回给玩家 发送登录消息给map
	CGameLogic::GetInstance().MapLayerLoginAgainByPlayer(player);

	// 进入游戏正确回复
	CGlobalConfig gconf = CTPLManager::GetInstance().global_config();
	Json::Value response = gconf.GetDisFunction();
	response["msgid"] = g2c_player_enter_game_ret;
	response["ret"] = ::common::SUCCEED;
	response["playerId"] = playerId;
	std::string res = JsonWriter(response);
	GameServer::GetInstance().client_msg_dispatch(res, fd, g2c_player_enter_game_ret);

	//player->SendDailyMissionList();//解锁新日常任务推送

	player->CheckSystemMailToSend();

	//原先login_finish
	{
		player->SetNotEmpty();
		
		player->SetPingTime(0, 0);
		player->SendServerInitFinished();

		if (MapSlot::GetInstance().GetLuaManagerPtr()->TryLock())
		{
			int32_t _ret = MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_PlayerCommonScript,
				LUA_PlayerLoginFinished, (int32_t)player->GetPlayerId());
		}
		else
		{
			int32_t _ret = MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_PlayerCommonScript,
				LUA_PlayerLoginFinished, (int32_t)player->GetPlayerId());
		}
	}
	//原先的playerEnterGame
	{
		if (MapSlot::GetInstance().GetLuaManagerPtr()->TryLock())
		{
			int32_t _ret = MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_PlayerCommonScript,
				LUA_PlayerEnterGame, (int32_t)player->GetPlayerId());
		}
		else
		{
			int32_t _ret = MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunction(LUA_PlayerCommonScript,
				LUA_PlayerEnterGame, (int32_t)player->GetPlayerId());
		}
	}

	// 抛出玩家进入游戏事件
	player_enter_game_event(*player);

	return common::SUCCEED;
}

void CGameLogic::PlayerChangeName(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t playerId = m_jv["playerId"].asInt();
	int32_t account = m_jv["account"].asInt();
	std::string name = m_jv["arg1"].asString();

	Json::Value response;
	response["msgid"] = login_change_name_ret;
	response["ret"] = 0;

	//屏蔽字检查

	if ((int32_t)name.length() > 32)
	{
		LOG_INFO("default", "check name length err[%d > 32]", name.length());
		response["ret"] = ::common::ERR_NAME_HAS_SPEC_USE_OTHER;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, login_change_name_ret);
		return;
	}

	//判断是否有回车换行
	std::string role_name_str = name.c_str();
	std::string::size_type idx = role_name_str.find("\n");
	if (idx != std::string::npos)
	{
		LOG_INFO("default", "name have dirtyword[%s]", name.c_str());
		response["ret"] = ::common::ERR_NAME_HAS_SPEC_USE_OTHER;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, login_change_name_ret);
		return;
	}

	if (CDirtyWord::GetInstance().OI_Dirty_Check(3, (char*)name.c_str(), 0) != 0)
	{
		LOG_INFO("default", "name have dirtyword[%s]!", name.c_str());
		response["ret"] = ::common::ERR_NAME_HAS_SPEC_USE_OTHER;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, login_change_name_ret);
		return;
	}


	// 判断名字是否重复
	CPlayerInfo* playerinfo = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerName(name);
	if ( playerinfo != NULL )
	{
		response["ret"] = ::common::ERR_NAME_USED_PLEASE_CHANGE;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, login_change_name_ret);
		return;
	}

	playerinfo = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(player.GetPlayerId());
	if (playerinfo == NULL)
	{
		response["ret"] = ::common::ERR_UNKNOWN;
		std::string sendStr = JsonWriter(response);
		player.SendToClient(&sendStr, login_change_name_ret);
		return;
	}

	// 如果不是首次改名，要收钱
	if (player.GetChangeName() > 0)
	{
		// 判断消耗
		if (player.GetCurrency(Fixed1024::CURRENCY_DIAMOND) < 50)
		{
			response["ret"] = ::common::ERR_NOT_ENOUGH_DIAMOND;
			std::string sendStr = JsonWriter(response);
			player.SendToClient(&sendStr, login_change_name_ret);
			return;
		}

		// 先消耗钻石，再创建公会
		int32_t ret = player.ChangeNumber(Fixed1024::CURRENCY_DIAMOND, 50);
		if (ret != ::common::SUCCEED)
		{
			LOG_ERROR("default", "change number err player[%d] ret[%d]", player.GetPlayerId(), ret);
			response["ret"] = ::common::ERR_NOT_ENOUGH_DIAMOND;
			std::string sendStr = JsonWriter(response);
			player.SendToClient(&sendStr, login_change_name_ret);
			return;
		}
	}

	std::string old_name(player.GetName());
	playerinfo->set_name(name);
	player.SetName(name.c_str());
	player.SetChangeName(player.GetChangeName() + 1);

	CSceneLogic::GetInstance().SetPlayerSomeInfoToRedisDBByPlayerId(playerId, "name", name, 0);
	CSceneLogic::GetInstance().SetPlayerSomeInfoToRedisDBByPlayerId(playerId, "changeName", player.GetChangeName());

	CPlayerInfoMgr::GetInstance().PlayerChangeName(old_name, *playerinfo);

	response["diamond"] = player.GetCurrency(Fixed1024::CURRENCY_DIAMOND);
	response["name"] = name;
	std::string sendStr = JsonWriter(response);
	player.SendToClient(&sendStr, login_change_name_ret);

	CGameLogic::GetInstance().updatePlayerNewNameToDB(playerId, name);
}

void CGameLogic::MapPlayerLoginAgain(const common::CProxyHead& head, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();

	if (!m_jv.isMember("msgid"))
	{
		return;
	}

	uint32_t socketId = m_jv["_gate_fd"].asInt();// .GetFromSocketId();
	Player * player = CSceneLogic::GetInstance().GetPlayerBySocket(socketId);

	if (player == NULL) {
		LOG_ERROR("default", "map login again error socketid[%d]", socketId);
		return;
	}

	CGameLogic::GetInstance().MapLayerLoginAgainByPlayer(player);
}

// 发送给gate map 连接信息
void CGameLogic::G2GateChangeMapConnect(const common::CProxyHead& head, const CJsonMessageBase& msg)
{
	Json::Value m_jv = msg.GetJsonValue();
	m_jv["msgid"] = g_gate_change_map_do;
	m_jv["ret"] = 0;

	// 启动game 设置map 连接服务
	uint32_t map_area = m_jv["map_area"].asUInt();
	CProxyClientService::GetInstance().SetMapArea(map_area);


	std::string str = JsonWriter(m_jv);
	send_gate_2_gate(str, g_gate_change_map_do);
}

void CGameLogic::SyncHeroGame2Map(const common::CProxyHead& head, const CJsonMessageBase& msg)
{
	const Json::Value m_jv = msg.GetJsonValue();
	uint32_t heroId = m_jv["heroId"].asUInt();
	uint32_t playerId = m_jv["playerId"].asUInt();

	Player* player = CSceneLogic::GetInstance().GetPlayerByPlayerID(playerId);
	if (NULL == player) {
		return;
	}
	Json::Value empty_json;
	player->SendToMapUpdateHeroInfo(heroId, empty_json, 1);
}

void CGameLogic::ExecSql(const char* sql, int split_id)
{
	if (sql == NULL) return;

	Json::Value request;
	request["sql"] = std::string(sql);

	std::string sendstr = JsonWriter(request);

	send_2_db(ID_DBSqlExecResquest, sendstr, split_id);
}

void CGameLogic::updatePlayerNewNameToDB(int32_t playerid, std::string& name)
{
	char sql[512] = { 0 };
	snprintf(sql, sizeof(sql), "UPDATE tb_player_info SET name='%s' WHERE playerId='%d'",
		name.c_str(), playerid);

	ExecSql(sql, playerid);
}



void CGameLogic::PlayerNumReportStart()
{
	// 每5秒同步一次玩家人数到login
	player_num_timer_.TimerInit(3 * 1000);
	player_num_timer_.TimerStart();
}

void CGameLogic::updateOnlinePlayerCountToDB()
{
	int32_t areaId = GameHostManager::GetInstance().GetServerAreaId();
	int32_t online = CSceneLogic::GetInstance().GetOnlineCount();
	int32_t now_time = CUR_SEC;
	char sql[512] = { 0 };
	snprintf(sql, sizeof(sql), "replace into tb_base_online(areaId, gameonline, gameupdate_time) values(%d,%d, %d)",
		areaId, online, now_time);

	ExecSql(sql, 0);
}

void CGameLogic::MapLayerLoginAgainByPlayer(Player* player)
{
	if (player == NULL) {
		LOG_ERROR("default", "map login again error player is null");
		return;
	}
	Json::Value target;
	target["ret"] = ::common::SUCCEED;
	
	target["playerId"] = player->GetPlayerId();
	target["account"] = player->GetAccount();
	target["_gate_fd"] = player->GetSocketId();
	target["_area_id"] = player->GetArea();
	target["heroId"] = player->GetHeroId();
	target["skinId"] = player->GetHeroSkinId();
	target["playerLv"] = player->GetLevel();

	Json::Value hero_pro;
	player->SendToMapUpdateHeroInfo(0, hero_pro, 0);
	hero_pro["set_type"] = 1;
	target["hero_property"] = hero_pro;

	target["msgid"] = g_map_player_login_req;
	std::string send_str = JsonWriter(target);
	send_2_map(g_map_player_login_req, send_str);

}
//====================================================================================
void CPlayerCountReportTimer::TimerActive()
{
	TimerStart();
	try {
		Json::Value report;
		report["msgid"] = g2l_player_count_report;
		report["playernum"] = CSceneLogic::GetInstance().GetOnlineCount();
		std::string sendstr = JsonWriter(report);
		send_2_login(g2l_player_count_report, sendstr);

		CGameLogic::GetInstance().updateOnlinePlayerCountToDB();
	}
	catch (...) {
		LOG_ERROR("default", "CPlayerCountReportTimer::TimerActive, error");
	}
}
